/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ortus.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author Aaron
 */
public class string {
	public static String CleanString(String s1) {
		s1 = s1.toLowerCase();

		if (s1.startsWith("the ") || s1.startsWith("the.") || s1.startsWith("the_")) {
			s1 = s1.substring(4).trim();
		}
		if (s1.startsWith("a ") || s1.startsWith("a.") || s1.startsWith("a_")) {
			s1 = s1.substring(2).trim();
		}
		if (s1.startsWith("an ") || s1.startsWith("an.") || s1.startsWith("an_")) {
			s1 = s1.substring(3).trim();
		}

		return s1;
	}

	public static String CleanStringPostpend(String s1) {

		String s2 = s1.toLowerCase();

		if (s2.startsWith("the ") || s2.startsWith("the.") || s2.startsWith("the_")) {
			s1 = s1.substring(4) + ", " + s1.substring(0, 3);
		}
		if (s2.startsWith("a ") || s2.startsWith("a.") || s2.startsWith("a_")) {
			s1 = s1.substring(2) + ", " + s1.substring(0, 1);
		}
		if (s2.startsWith("an ") || s2.startsWith("an.") || s2.startsWith("an_")) {
			s1 = s1.substring(3) + ", " + s1.substring(0, 2);
		}

		return s1;
	}

        public static String decodeString(String x) {
//            DebugLog(TRACE2, "decodeString: parsing: " + x);
            Pattern pattern = Pattern.compile("&#x([^;]+);");
            Matcher matcher = pattern.matcher(x);
            StringBuffer sb = new StringBuffer(x.length());
            while (matcher.find())
               matcher.appendReplacement(sb, Matcher.quoteReplacement("%" + matcher.group(1)));
            matcher.appendTail(sb);

            pattern = Pattern.compile("&#([^;]+);");
            matcher = pattern.matcher(sb);
            StringBuffer sb2 = new StringBuffer(sb.length());
            while (matcher.find())
               matcher.appendReplacement(sb2, Matcher.quoteReplacement("%" + String.format("%02X", Integer.parseInt(matcher.group(1)))));
            matcher.appendTail(sb2);
            String result;
	    try {
            result = URLDecoder.decode(sb2.toString());
	    } catch ( Exception e) {
		    result = sb2.toString();
	    }
//	    DebugLog(TRACE2,"decodeString: returning: " + result);
            return result;
        }
}
